package capstone.tagit;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;

import android.util.Log;

/**
 * 
 * This is the old version of the server.  This class is intended to be replaced
 * by a protocol to communicate with the PHP based server.
 * The server that this connects to will disconnect the socket after one transaction.
 *
 */
public class AppClient {

	
	InetAddress server;
	Socket socket;
	int port;
	
	/**
	 * 
	 * The constructor for an AppClient object.  Takes server information
	 * and constructs an object which can be used to connect to a server.
	 * @param address	The IP address or URL of the server to connect to
	 * @param port	The port at which the server is listening
	 * 
	 */
	public AppClient(String address, int port){
		try {
			server = InetAddress.getByName(address);
			this.port = port;			
		} catch (Exception e) {}
	}
	/**
	 * 
	 * Queries the server for the current tags stored there.  Returns
	 * them all in a single newline delimited string.
	 * @return the list of current tags stored in the server.  A single newline-delimited string
	 */
	public String query(){
		socket = new Socket();
		Log.v("Client", "Just entered query");
		String tagsList = new String("");
		try {
			socket.connect(new InetSocketAddress(server, port), 50000);
			DataOutputStream os = new DataOutputStream(socket.getOutputStream());
			InputStream is = socket.getInputStream();
			BufferedReader fromServer = new BufferedReader(new InputStreamReader(is));
			
			os.writeBytes("query\n");
			String tagLine = null;
			Log.v("Client","About to enter the while loop");
			while ((tagLine = fromServer.readLine()) != null){
				Log.v("Client","In the while loop");
				tagsList = tagsList.concat(tagLine + "\n");
			}
			socket.close();
		}catch(Exception e){}
		
		Log.v("Client","About to exit query");
		return tagsList;
		
	}
	
	/**
	 * Writes a tag to the server.
	 * @param tag the tag to write to the server.
	 */
	public void writeToServer(Tag tag) {
		socket = new Socket();
		try {
			socket.connect(new InetSocketAddress(server, port), 50000);
			DataOutputStream os = new DataOutputStream(socket.getOutputStream());
			os.writeBytes(tag.getInfoString(new SimpleDateFormat("yyyy.MM.dd \'at\' HH:mm:ss z")));
			socket.close();
		} catch (Exception e) {}
		
		
	}
	
	/**
	 * Closes the socket when done.  This is currently unnecessary, as the server
	 * closes the connection on its own.
	 */
	public void closeConnection(){
		try {
			socket.close();
		} catch (Exception e) {}
	}

}
